package com.hw.one.dam2.service;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.hw.one.dam2.dao.IWeatherDao;
import com.hw.one.dam2.entity.LampBlackBaseEntity;
import com.hw.one.dam2.param.RegionSiteParam;
import com.hw.one.dam2.util.UserSiteUtil;
import com.hw.one.ext.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hw.one.dam2.common.DataTypeEnum;
import com.hw.one.dam2.common.SiteTypeEnum;
import com.hw.one.dam2.dao.ILampBlackDao;
import com.hw.one.dam2.dao.IRegionSiteDao;
import com.hw.one.dam2.dao.ISmallAirDao;
import com.hw.one.dam2.entity.LampBlackEntity;
import com.hw.one.dam2.param.SmallAirParam;
import com.hw.one.ext.util.UserUtil;
import com.hw.one.util.DateTimeUtil;
import org.springframework.util.StringUtils;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/05/23 17:23.
 */
@Service(value = "lampBlackService")
public class LampBlackService implements ILampBlackService {

    @Autowired
    private ILampBlackDao lampBlackDao;

    @Autowired
    private IRegionSiteDao regionSiteDao;

    @Autowired
    private ISmallAirDao smallAirDao;

    @Autowired
    private IWeatherDao weatherDao;

    @Override
    public List<Map<String, Object>> findLampBlackMinuteNewDataBySiteCodes(List<String> siteCodeList) {
        List<Map> lampBlackList = lampBlackDao.findLampBlackNewMinuteDataBySiteCodeList(siteCodeList);

        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> resultMap = null;
        List<Object> lampNameList = new ArrayList<>();
        for (Map lampBlack : lampBlackList) {
//            if (1 == (int)lampBlack.get("ADDRESS")) {
//                // 暂时过滤掉处理前的数据
//                continue;
//            }
            if(lampNameList.contains(lampBlack.get("SITECODE") + "_" + lampBlack.get("ADDRESS"))){
                continue;
            }
            lampNameList.add(lampBlack.get("SITECODE") + "_" + lampBlack.get("ADDRESS"));
            resultMap = new HashMap<>();
            Map<String, Object> beforeOrAfter = new HashMap<>();
            resultMap.put("monitorTime", lampBlack.get("MONITORTIME"));
            resultMap.put("siteCode", lampBlack.get("SITECODE"));
            resultMap.put("snCode", lampBlack.get("SNCODE"));

            beforeOrAfter.put("concentration", lampBlack.get("CONCENTRATION"));
            beforeOrAfter.put("purifierState", (int)lampBlack.get("PURIFIERSTATE") == 1 ? "关" : "开");
            beforeOrAfter.put("blowerState", (int)lampBlack.get("BLOWERSTATE") == 1 ? "关": "开");
            beforeOrAfter.put("systemState", (int)lampBlack.get("SYATEMSTATE") == 1 ? "正常": "异常");
            beforeOrAfter.put("conlimit", lampBlack.get("CONLIMIT"));
            beforeOrAfter.put("cleanLiness", getCleanLessStr((int) lampBlack.get("CLEANLINESS")));
            beforeOrAfter.put("hum", lampBlack.get("HUM"));
            beforeOrAfter.put("temp", lampBlack.get("TEMP"));
            beforeOrAfter.put("address", lampBlack.get("ADDRESS"));
            if ("1".equals(String.valueOf(lampBlack.get("ADDRESS")))) {
                resultMap.put("before", beforeOrAfter);
            }
            if ("2".equals(String.valueOf(lampBlack.get("ADDRESS")))) {
                resultMap.put("after", beforeOrAfter);
            }
            boolean flag = false;
            // 循环结果集,判断之前是否已经有结果保存
            for (Map<String, Object> map : resultList) {
                if (lampBlack.get("SITECODE").equals(map.get("siteCode"))) {
                    // 如果有,就不插入结果集,直接放入之前的结果集里面
                    flag = true;
                    if ("1".equals(String.valueOf(lampBlack.get("ADDRESS")))) {
                        map.put("before", beforeOrAfter);
                    }
                    if ("2".equals(String.valueOf(lampBlack.get("ADDRESS")))) {
                        map.put("after", beforeOrAfter);
                    }
                }
            }
            if (!flag) {
                resultList.add(resultMap);
            }
        }
        return resultList;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public List<LampBlackEntity> findLampBlackDataByRegionCode(HttpServletRequest request) throws Exception {
        // 判断用户是否具有访问权限
        if (!UserSiteUtil.userIsNotContainSiteTypes("103")) {
            return new ArrayList<LampBlackEntity>();
        }
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String siteCodes = request.getParameter("siteCodes");

        Calendar calendar = Calendar.getInstance();

        if (null == endTime || "".equals(endTime)) {
            endTime = DateTimeUtil.getFormatDateStr(calendar.getTime(), "yyyy-MM-dd HH:00:00");
        }

        if (null == startTime || "".equals(startTime)) {
            // 近两天的数据
            calendar.add(Calendar.DAY_OF_MONTH, -2);
            startTime = DateTimeUtil.getFormatDateStr(calendar.getTime(), "yyyy-MM-dd HH:00:00");
        }
        // 数据类型：小时数据hourData;日数据 dayData
        String dataType = request.getParameter("dataType");
        dataType = null == dataType || "".equals(dataType) ? "hourData" : dataType;

        Map<String, Object> region = UserUtil.getRegion();
        String userRegionCode = (String) region.get("regionCode");
        String userRegionType = (String) region.get("regionType");

        /**
         * 根据当前登录用户区域，查询该区域的上级区域
         */
        List<Map<String, Object>> parentRegionList = regionSiteDao.findParentRegionInfoByRegionCode(userRegionCode);
        String cityCode = "";
        // 把登录用户所属省份、和市编码，读取出来
        for (Map<String, Object> parentRegionMap : parentRegionList) {
            String retionType = String.valueOf(parentRegionMap.get("regionType"));
            // 市级名称
            if ("20".equals(retionType)) {
                cityCode = String.valueOf(parentRegionMap.get("regionCode"));
                break;
            }
        }

        // 查询点位信息的参数Map
        RegionSiteParam siteParam = new RegionSiteParam();
        siteParam.setSiteType(SiteTypeEnum.LAMPBLACK_SITE.getValue());
        if (!StringUtils.isEmpty(siteCodes)) {
            siteParam.setSiteCodeList(Arrays.asList(siteCodes.split(",")));
        }
        siteParam.setRegionCode(userRegionCode);
//        Map<String, String> paraSiteMap = new HashMap<String, String>();
//        paraSiteMap.put("regionCode", userRegionCode);
//        paraSiteMap.put("siteType", SiteTypeEnum.LAMPBLACK_SITE.getValue());

        // 点位信息列表
        List<Map<String, Object>> siteInfoList = regionSiteDao.findSiteInfoByRegionCodeAndSiteType(siteParam);

        List<LampBlackEntity> returnList = new ArrayList<>();
        List<Map> lampBlackList = new ArrayList<>();
        if (siteInfoList == null || siteInfoList.size() == 0) {
            return returnList;
        }

        // 点位编码列
        List<String> pointCodeList = new ArrayList<String>();
        for (Map<String, Object> siteMap : siteInfoList) {
            pointCodeList.add(String.valueOf(siteMap.get("siteCode")));
        }

        SmallAirParam smallAirParam = new SmallAirParam();
        smallAirParam.setSiteCodes(pointCodeList);
        smallAirParam.setStartTime(startTime);
        smallAirParam.setEndTime(endTime);
        if (DataTypeEnum.MINUTE_DATA.getValue().equals(dataType)) {
            // 分钟数据
            lampBlackList = smallAirDao.findSmallMinuteDataByPointCodeAndTime(smallAirParam);
        }else if (DataTypeEnum.HOUR_DATA.getValue().equals(dataType)) {
            // 小时数据
            lampBlackList = smallAirDao.findSmallHourDataByPointCodeAndTime(smallAirParam);
            for (Map lampBlack : lampBlackList) {
                lampBlack.put("MONITORTIME", lampBlack.get("MONITORTIME").toString().substring(0, 16));
            }
        }
        // 查询实时天气，填充国控站，小型站温度、湿度、风向、风速数据
        Map cityLiveWeatherMap = (Map) weatherDao.findCityLiveWeatherByRegionCode(cityCode);
        LampBlackEntity lampBlackEntity = null;
        int index = 1;
        for (Map lampBlack : lampBlackList) {
            lampBlackEntity = new LampBlackEntity();
            String siteCode = String.valueOf(lampBlack.get("SITECODE"));
            lampBlackEntity.setIndex(String.valueOf(index++));
            lampBlackEntity.setMonitorTime(String.valueOf(lampBlack.get("MONITORTIME")));
            lampBlackEntity.setSiteCode(siteCode);
            lampBlackEntity.setSnCode(String.valueOf(lampBlack.get("SNCODE")));

            LampBlackBaseEntity before = new LampBlackBaseEntity();
            before.setTemp(String.valueOf(lampBlack.get("TEMP")));
            before.setHum(String.valueOf(lampBlack.get("HUM")));
            before.setConcentration(String.valueOf(lampBlack.get("CONCENTRATION")));
            before.setConLimit(String.valueOf(lampBlack.get("CONLIMIT")));
            before.setPurifierState("1".equals(String.valueOf(lampBlack.get("PURIFIERSTATE"))) ? "关" : "开");
            before.setBlowerState("1".equals(String.valueOf(lampBlack.get("BLOWERSTATE"))) ? "关" : "开");
            before.setCleanLiness(getCleanLessStr((int) lampBlack.get("CLEANLINESS")));
            before.setAddress(String.valueOf(lampBlack.get("ADDRESS")));
            before.setSystemState((int) lampBlack.get("SYATEMSTATE") == 1 ? "正常": "异常");
            if ("1".equals(before.getAddress())) {
                lampBlackEntity.setBefore(before);
            }
            if ("2".equals(before.getAddress())) {
                lampBlackEntity.setAfter(before);
            }
            for (Map siteInfo : siteInfoList) {
                if (siteCode.equals(siteInfo.get("siteCode").toString())){
                    lampBlackEntity.setCompanyName(String.valueOf(siteInfo.get("siteName")));
                    lampBlackEntity.setCityName(String.valueOf(siteInfo.get("RegionName")));
                }
            }
            // 判断前探头和后探头
            boolean flag = true;
            for (LampBlackEntity lampBlackEntity1 : returnList) {
                if (lampBlackEntity1.getSiteCode().equals(lampBlackEntity.getSiteCode()) && lampBlackEntity1.getMonitorTime().equals(lampBlackEntity.getMonitorTime())) {
                    flag = false;
                    if ("1".equals(before.getAddress())) {
                        lampBlackEntity1.setBefore(before);
                    }
                    if ("2".equals(before.getAddress())) {
                        lampBlackEntity1.setAfter(before);
                    }
                }
            }


            if (flag) {
                returnList.add(lampBlackEntity);
            }
        }
        return returnList;
    }

    private String getCleanLessStr(int cleanLess) {
        switch (cleanLess) {
            case 1:
                return "清洁";
            case 2:
                return "较清洁";
            case 3:
                return "脏";
            case 4:
                return "较脏";
            case 5:
                return "极脏";
            default:
                return "-";
        }
    }
}
